window.onload = function() {
        init()
        internationalizes()
        registerNotifyCallBack("registerNotifyCallBack")
        hilink.changeTitleStyle(2)
    }
    //状态：未连接 连接中 工作中 暂停
var status_title = "未连接"
    //展示区数据
    //工作时长  分钟
var work_time = ""; //工作时长
//剩余电量  %
var battery = ""; //电量
//速度 转/分
var speed = ""; //转速

//控制区数据
//是否开启加热模式 true false
var warmon = false; //加热模式
var opened = "" //已开启
    //倒计时 格式 00:00 分钟
var listName = "" //倒计时
    // 0;1;2;3;4;5
var sliderStatus = "0"; //挡位

var power_img = "./static/img/power.png" //工作状态
var timer_img = "./static/img/ic_countdown_blue.png" //倒计时 
var warm_img = "./static/img/ic_enum_off.png"

// 工作状态判断
var workstatus = "on"; //开关   
// 蓝牙状态判断 
var ble_status = "connect"; //连接未连接的状态


window.sendMsgCallback = res => {

        // ble_status = "connect";
        // workstatus = "on"
        // TODO: console.log(res);
        // if (res) {

        // }
        // refreshUI()
    } //不动  


window.registerNotifyCallBack = res => {
    // console.log(res + "index ");
}


function assignment() {
    speed = result.speed;
    work_time = result.runTime
    battery = result.power
    refreshUI()
}


function disconnects() {
    app.classList.add("disconnect")
}

function disabled() {
    // app.classList.remove("disconnect")
    app.classList.add("disabled")
}

function enable() {
    app.classList.remove("disabled")
    app.classList.remove("disconnect")
}

function blackmode() {
    app.classList.add("dark")
}
//点击使工作状态变化
function changemode() {
    if (workstatus == "on" && ble_status == "connect") {
        workstatus = "off";
        sendBle(MESSAGE_SEND.SPEED_LEVEL, '{"cmd":"81","value":"00"}', "sendMsgCallback")
            // refreshUI()
    } else if (workstatus == "off" && ble_status == "connect") {
        workstatus = "on";

        sendBle(MESSAGE_SEND.SPEED_LEVEL, '{"cmd":"81","value":"01"}', "sendMsgCallback")
    }
    stripLeft.style.width = 0
    slider.style.left = -12 + "px"
}
// 点击重新连接的时候调用这个方法


function link() {
    if (ble_status == "disconnect") {}
    connectDevice();
}


function refreshUI() {
    if (ble_status == "disconnect") {
        disconnect()
    } else if (ble_status == "connect") {
        refreshWhenWorkStatusChange()
    } else if (ble_status == "connecting") {
        connecting()
    }
    document.getElementById("statustitle").innerHTML = status_title;
    document.getElementById("work_time").innerHTML = work_time;
    document.getElementById("battery").innerHTML = battery;
    document.getElementById("speed").innerHTML = speed;
    document.getElementById("listName").innerHTML = listName;
    document.querySelector(".sliderStatus").innerHTML = sliderStatus + "档";
    document.getElementById("power_img").setAttribute('src', power_img);
}
var spinner_cd = document.querySelector(".spinner_cd")

function func() {
    let val = spinnerWrap.style.display;
    if (val === 'block') {
        spinnerWrap.style.display = 'none';
    } else {
        spinnerWrap.style.display = 'block';
    }
}


//蓝牙已连接状态下进行工作状态判断
function refreshWhenWorkStatusChange() {
    document.getElementById("restart").style.display = "none";
    document.getElementById("power_img").style.display = "display";
    if (workstatus == "off") {
        pause()
    } else if (workstatus == "on") {
        work()
    }
}

//disconnect状态 这里修改值
function disconnect() {
    // document.getElementsByClassName("statustitle")[0].innerHTML = statustitle
    status_title = "未连接"
    work_time = "--"
    speed = "--"
    battery = "--"
    warm_img = "./static/img/ic_enum_off.png"
    warmon = false
    listName = ""
    timer_img = "./static/img/ic_countdown_blue.png"
    mode_disconnect()
}
// 这里修改风格，以及监听事件，不改值
function mode_disconnect() {
    disconnects()
    disabled()
    document.getElementById("power_img").style.display = "none";
    //加热模式,除了颜色，右侧图片，还有点击监听
    document.getElementById("warm_ctrl").removeEventListener('click', setwarm)
        // 倒计时，除了颜色，右侧图片，还有点击监听
    document.getElementById("massagelevel").style.display = "none";
    spinner_cd.addEventListener("click", func);
    document.querySelector(".rang").classList.add("person");
}
//暂停状态，这里修改值
async function pause() {
    status_title = "暂停"
    power_img = "./static/img/ic_power_02.png"
    warmon = false
    opened = ""
    listName = ""
    sliderStatus = "0"
    await mode_pause()
}
// 暂停状态，这里修改样式和模式
function mode_pause() {
    // enable()
    disabled()
        //加热模式,除了颜色，右侧图片，还有点击监听
    document.querySelector(".rang").classList.add("person");
    spinner_cd.removeEventListener("click", func)
    document.getElementById("restart").style.display = "none";
    document.getElementById("gearsList").style.display = "none"
    document.getElementById("warm_ctrl").removeEventListener('click', setwarm)
    document.querySelector("#opening").innerHTML = ""
        // 倒计时，除了颜色，右侧图片，还有点击监听
    document.getElementById("listName").style.display = "none"
    document.getElementById("massagelevel").style.display = "none";
    spinner_cd.addEventListener("click", func);
    // console.log("mode_pause");
    // 按摩力度，除了颜色，进度条颜色，进度条事件监听

}
// 工作状态，这里修改值
function work() {
    status_title = "工作中"
    power_img = "./static/img/power.png"
    mode_work()
}
// 工作状态，这里修改样式和模式
function mode_work() {
    enable()
        //加热模式,除了颜色，右侧图片，还有点击监听
    document.querySelector(".rang").classList.remove("person");
    document.getElementById("restart").style.display = "none";
    document.getElementById("power_img").style.display = "block"
        // 倒计时，除了颜色，右侧图片，还有点击监听
    document.getElementById("listName").style.display = "block"
    document.getElementById("massagelevel").style.display = "block";
    document.getElementById("warm_ctrl").addEventListener('click', setwarm)
    spinner_cd.removeEventListener("click", func)
        // console.log("mode_work");
}

// 连接中状态，这里修改值
function connecting() {
    status_title = "连接中"
    work_time = "--"
    speed = "--"
    battery = "--"
    listName = ""
    warm_img = "./static/img/ic_enum_off.png"
    power_img = "./static/img/loading.png"
    if (window.hilink) {
        var dark = hilink.getDarkMode();
        if (dark == 2) { //暗黑模式
            power_img = "./static/img/loading_dark.png"
            hilink.changeTitleStyle(1)
        } else {
            power_img = "./static/img/loading.png"
            hilink.changeTitleStyle(2)
        }
    }
    warmon = false
        // document.getElementById("power_img").setAttribute('src', "./img/loading.png");
    mode_connecting()
    timer_img = "./static\img\ic_countdown_blue.png"
}
// 连接中状态，这里修改样式和模式
function mode_connecting() {
    disconnects()
    disabled()
    document.querySelector(".rang").classList.add("person");
    document.getElementById("power_img").removeEventListener('click', changemode)
    document.getElementById("restart").style.display = "none";
    document.getElementById("warm_ctrl").removeEventListener('click', setwarm)
        // 倒计时，除了颜色，右侧图片，还有点击监听
    spinner_cd.addEventListener("click", func);
    // 按摩，除了颜色，右侧图片，还有点击监听
    document.getElementById("massagelevel").style.display = "none";

    // 按摩力度，除了颜色，进度条颜色，进度条事件监听
}

// 加热模式开关-----控制设备区
// warmmode()

function setwarm() {
    warmon = !warmon
    warmmode()
}

function warmmode() {
    if (warmon) { //开启
        document.getElementById("warm_img").setAttribute('src', "./static/img/ic_pattern_on.png");

        document.querySelector("#opening").innerHTML = "已开启"
        sendBle(MESSAGE_SEND.WARM, '{"cmd":"83","value":"01"}', "sendMsgCallback")

    } else { //关闭
        document.getElementById("warm_img").setAttribute('src', "./static/img/ic_enum_off.png");
        document.querySelector("#opening").innerHTML = "";
        sendBle(MESSAGE_SEND.WARM, '{"cmd":"83","value":"00"}', "sendMsgCallback")
    }
}

// 倒计时列表弹窗
var spinnerWrap = document.getElementsByClassName("spinnerWrap")[0];
var gears = ["关闭", "5", "10", "15"];
var content = "";

// 动态增加列表标签
for (let i = 0; i < gears.length; i++) {
    if (gears[i] === "关闭") {
        listName = ""
        content = content + "<li  class='spinnerList'>" + gears[i] + "</li>";
        document.getElementById("gearsList").innerHTML = content
    } else {
        listName = gears[i] + "分钟"
        content = content + "<li  class='spinnerList'>" + gears[i] + "分钟" + "</li>";
        document.getElementById("gearsList").innerHTML = content
    }
}

//获取所有spinnerList节点
var spinnerList = document.getElementsByClassName("spinnerList")
for (let i = 0; i < spinnerList.length; i++) {
    (function(n) {
        spinnerList[i].onclick = function() {
            if (spinnerList[n].innerHTML === "关闭") {
                listName = ""
                document.querySelector("#listName").innerHTML = ""
            } else {
                // console.log(spinnerList[n])
                if (spinnerList[n].innerHTML === "5分钟") {
                    document.querySelector("#listName").innerHTML = "5分钟"
                } else if (spinnerList[n].innerHTML === "10分钟") {
                    document.querySelector("#listName").innerHTML = "10分钟"
                } else if (spinnerList[n].innerHTML === "15分钟") {
                    document.querySelector("#listName").innerHTML = "15分钟"
                }
                listName = spinnerList[n].innerHTML.substring(0, spinnerList[n].innerHTML.lastIndexOf("分钟")) + "分钟"
            }
            sendBle(MESSAGE_SEND.SET_TIME, '{"cmd":"84","value":"0' + i + '"}', "sendMsgCallback")
        }
    })(i)
}

// 按摩力度——滑动条
let rang = document.querySelector(".rang")
let slider = document.querySelector(".slider")
let stripLeft = document.querySelector(".stripLeft")
let target = rang.offsetWidth
window.addEventListener('resize', function(e) {
    target = rang.offsetWidth //滑动条滑动的最大距离
});

let part = target / 5
stripLeft.style.width = (part * sliderStatus) + "px"
slider.style.left = (part * sliderStatus) - 12 + "px"

rang.addEventListener("click", function(e) {
    let part = target / 5
    stripLeft.style.width = (part * Math.floor(e.offsetX / (target / 6))) + "px"
    slider.style.left = (part * Math.floor(e.offsetX / (target / 6))) - 12 + "px"
    sliderStatus = Math.floor(e.offsetX / (target / 6))
    let sliderStatusInfo = Math.floor(e.offsetX / (target / 6))

    sendBle(MESSAGE_SEND.SPEED_LEVEL, '{"cmd":"82","value":"0' + sliderStatusInfo + '"}', "sendMsgCallback")

})

rang.addEventListener("touchmove", function(e) {
    let part = target / 5
    if (e.changedTouches[0].pageX - rang.offsetLeft < target && e.changedTouches[0].pageX - rang.offsetLeft > 0) {
        stripLeft.style.width = (part * Math.floor((e.changedTouches[0].pageX - rang.offsetLeft) / (target / 6))) + "px"
        slider.style.left = (part * Math.floor((e.changedTouches[0].pageX - rang.offsetLeft) / (target / 6))) - 12 + "px"
        sliderStatus = Math.floor((e.changedTouches[0].pageX - rang.offsetLeft) / (target / 6))
        let sliderStatusInfo = Math.floor((e.changedTouches[0].pageX - rang.offsetLeft) / (target / 6))

        sendBle(MESSAGE_SEND.SPEED_LEVEL, '{"cmd":"82","value":"0' + sliderStatusInfo + '"}', "sendMsgCallback")
    }
})



function getDarkMode() {
    if (window.hilink) {
        var dark = hilink.getDarkMode();
        if (dark == 2) { //暗黑模式
            app.classList.add("dark");
        } else {
            app.classList.remove("dark")
        }
    }
}
getDarkMode();

function internationalizes() {
    this.currentLanguage = (function getAppLanguage() {
        // 判定规则:如果不是以'zh-'开始则显示为en-US
        let language,
            defualtLanguage = 'zh-CN';
        let reg = /^zh-/i;
        if (navigator && navigator.language) {
            language = reg.test(navigator.language) ? defualtLanguage : 'en-US';
        } else {
            language = defualtLanguage;
        }
        return language;
    })();

    if (this.currentLanguage !== 'zh-CN') {
        this.document.getElementById("restart").innerHTML = "reconnect"
        if (ble_status == "disconnect") {
            this.document.getElementById("statustitle").innerHTML = "disconnect"
        } else if (ble_status == "connecting") {
            this.document.getElementById("statustitle").innerHTML = "connecting"
        } else if (ble_status == "connect" && workstatus == "on") {
            this.document.getElementById("statustitle").innerHTML = "working"
        } else if (ble_status == "connect" && workstatus == "off") {
            this.document.getElementById("statustitle").innerHTML = "pause"
        }
        this.document.getElementById("min").innerHTML = "minutes"
        this.document.getElementById("workTime").innerHTML = "worktime"
        this.document.getElementById("batteryinfo").innerHTML = "dump energy"
        this.document.getElementById("min2").innerHTML = "rad/min"
        this.document.getElementById("speedinfo").innerHTML = "speed"
        this.document.getElementById("warm").innerHTML = "heating mode"
        this.document.getElementById("opening").innerHTML = "enabled"
        this.document.getElementById("classctr").innerHTML = "countdown"
        this.document.getElementById("speedinfo").innerHTML = "speed"
        this.document.getElementById("massage").innerHTML = "message force"
        this.document.getElementById("spinnerList")[0].innerHTML = "5" + "minutes"
        this.document.getElementById("spinnerList")[1].innerHTML = "10" + "minutes"
        this.document.getElementById("spinnerList")[2].innerHTML = "15" + "minutes"
        this.document.getElementById("spinnerList")[3].innerHTML = "close"
        this.document.querySelector(".sliderStatus").innerHTML = sliderStatus + "level";
        this.document.getElementsByClassName("progressDes")[0].innerHTML = 'Connecting…'
        this.document.getElementsByClassName("failConnect")[0].innerHTML = 'Unable to connect'
        this.document.getElementsByClassName("details")[0].innerHTML = 'While connecting, make sure:'
        this.document.getElementsByClassName("details")[1].innerHTML = '1.The phone\'s Bluetooth is enabled.'
        this.document.getElementsByClassName("details")[2].innerHTML = '2.The device is within 5 meters of the phone.'
        this.document.getElementsByClassName("details")[3].innerHTML = '3.The phone is connected to the Internet.'
        this.document.getElementsByClassName("details")[4].innerHTML = '4.The device is not paired with the current account before.'
        this.document.getElementsByClassName("btn")[0].innerHTML = 'Try again'
    }
}